#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "Log.hpp"
#include "Thread.hpp"
#include "Mutex.hpp"
#include "Cond.hpp"

namespace ThreadPoolModule
{
    using namespace ThreadModlue;
    using namespace LogModule;
    using namespace MutexModule;
    using namespace CondModule;

    static const int gnum = 5;

    template <typename T>
    class ThreadPool
    {
    private:
        void WakeUpAllThread()
        {
            LockGuard lockgurad(_mutex);//为什么要加锁？访问了临界资源_sleepnum
            if(_sleepnum)//等待队列有线程在等待
                _cond.Broadcast();
            LOG(LogLevel::INFO)<<"Wake up all threads";
        }

        void WakeUpOne()
        {
            _cond.Signal();
            LOG(LogLevel::INFO)<<"Wake up one threads";
        }

        ThreadPool(int num = gnum) : _num(num),_isrunning(false),_sleepnum(0)
        {
            for (int i = 0; i < num; i++)
            {
                _threads.emplace_back(
                    [this]()
                    {
                        HandlerTask();
                    });
            }
        }

        void Start()
        {
            if(_isrunning) return;//已经运行起来了就不用start了
            _isrunning = true;
            for(auto& thread : _threads)
            {
                thread.Start();
                LOG(LogLevel::INFO)<<"Start new thread success:"<<thread.Name();
            }
        }

        //构造函数和Start都放私有，不允许直接在外部调用
        //禁用拷贝构造和=运算符重载
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;
    
    public:
        //仅能通过该静态函数来获取唯一实例
        static ThreadPool<T>* GetInstance()
        {
            //2.为什么这里还要判断？第一次创建后若每次都要申请锁，效率低
            if(inc == nullptr)
            {
                //1.为什么要加锁？防止多个线程同时进入后都创建单例
                LockGuard lockguard(_lock);
                LOG(LogLevel::DEBUG)<<"获取单例";
                if(inc == nullptr)
                {
                    LOG(LogLevel::DEBUG)<<"首次获取单例，创建";
                    inc = new ThreadPool<T>;
                    inc->Start();
                }
            }
            return inc;
        }
        
        void Stop()
        {
            if(!_isrunning) return;
            _isrunning = false;

            //唤醒所有进程，确保任务队列为空
            WakeUpAllThread();
        }

        void Join()
        {
            for(auto& thread:_threads)
            {
                thread.Join();
            }
        }

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                T t;//任务对象
                {
                    LockGuard lockguard(_mutex);
                    //退出条件是：a.队列为空 && b.线程退出
                    while(_taskq.empty() && _isrunning)
                    {
                        _sleepnum++;
                        _cond.Wait(_mutex);
                        _sleepnum--;
                    }
                    //被唤醒后处理队列剩余任务后退出
                    if(_taskq.empty() && !_isrunning)
                    {
                        LOG(LogLevel::INFO)<<name<<"线程池退出";
                        break;
                    }
                    //到此处一定有任务
                    t = _taskq.front();
                    _taskq.pop();
                }
                t();//处理任务，不需要在临界区处理，否则需要长时间后才解锁，效率低
            }
        }

        bool Enqueue(const T& in)
        {
            if(_isrunning)
            {
                LockGuard lockgurad(_mutex);
                _taskq.push(in);
                if(_threads.size() == _sleepnum)//只有任务队列为空线程才会进入等待队列
                    WakeUpOne();
                return true;
            }
            return false;
        }

        ~ThreadPool() {}

    private:
        int _num; // 线程池中线程的个数
        std::vector<Thread> _threads;//管理线程
        std::queue<T> _taskq;//管理任务

        Cond _cond;
        Mutex _mutex;

        bool _isrunning;//线程池是否还在运行
        int _sleepnum;//等待队列中线程的个数

        static ThreadPool<T>* inc;//单例指针
        static Mutex _lock;//管理单例指针的锁
    };

    //静态变量外部初始化
    template<typename T>
    ThreadPool<T>* ThreadPool<T>::inc = nullptr;

    template<typename T>
    Mutex ThreadPool<T>::_lock;
}